package com.k3cloud.json.factory;

import cn.hutool.extra.spring.SpringUtil;

import com.k3cloud.base.service.ConstructionHttpClientService;
import com.k3cloud.base.type.ConstructionInterfaceType;
import com.k3cloud.base.type.OutJsonTypeEnum;
import com.k3cloud.json.utils.ConstructionHttpClientJsonUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ConstructionOutJsonFactory {

    public Map<String,Object> getOutJsonData(String code, String name, OutJsonTypeEnum outJsonTypeEnum, Map<String,Object> parameters, Map<String,Object> bomKeyValue)throws Exception{

        Map<String, ConstructionHttpClientService> constructionServices= SpringUtil.getBeansOfType(ConstructionHttpClientService.class);
        ConstructionHttpClientService constructionHttpClientService=null;

        if(constructionServices!=null){
            for(Map.Entry<String,ConstructionHttpClientService> entity: constructionServices.entrySet()){
                ConstructionInterfaceType constructionInterfaceType=entity.getValue().getClass().getAnnotation(ConstructionInterfaceType.class);
                if(constructionInterfaceType.defaultValue().equals(outJsonTypeEnum.value())){
                    constructionHttpClientService=entity.getValue();
                    break;
                }
            }
        }
        if(constructionHttpClientService!=null){
            Map<String,Object> keyValue=new HashMap<>();
            if(parameters.size()>0){
                Map<String,Object> inMap=constructionHttpClientService.getInSettingMap(code, name);
                for(Map.Entry<String,Object> entity: parameters.entrySet()){
                    Map<String,Object> part= (Map<String, Object>) entity.getValue();
                    for(Map.Entry<String,Object> inEntity: inMap.entrySet()){
                        ConstructionHttpClientJsonUtils.setInTree((List<Map<String, Object>>) inEntity.getValue(), part.get(inEntity.getKey()), keyValue);
                    }
                }
            }

            keyValue.putAll(bomKeyValue);
            Map<String,Object> saveMateriel=new HashMap<>();
            List<Map<String, Object>> outSettingList=constructionHttpClientService.getOutSettingList(code, name);
            ConstructionHttpClientJsonUtils.getOutTree(outSettingList,saveMateriel,keyValue,0);
            return saveMateriel;
        }

        return null;
    }

}
